package com.yj.shortLink;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class ShortLinkServiceImpl implements ShortLinkService {

    private Cache<String, UrlMap> shortLinkCache = CacheUtil.newLRUCache(10000);


    @Autowired
    private ShortLinkUtil shortLinkUtil;

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public String createShortLink(String longUrl) {
        String shortLink = shortLinkUtil.generateShortLink(longUrl);
        int id = atomicInteger.incrementAndGet();
        UrlMap urlMap = new UrlMap(id, shortLink, longUrl, new Date());
        shortLinkCache.put(shortLink, urlMap);
        return shortLink;
    }

    @Override
    public String parseShortLink(String shortUrl) {
        UrlMap urlMap = shortLinkCache.get(shortUrl);
        if (urlMap != null) {
            return urlMap.getLongUrl();
        }
        return null;
    }

    @Override
    public boolean validateShortLink(String shortUrl) {
        UrlMap urlMap = shortLinkCache.get(shortUrl);
        if (urlMap != null) {
            return true;
        }
        return false;
    }
}
